package jaux.tank.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import jaux.tank.bean.entity.system.OperationLog;
import jaux.tank.dao.system.OperationLogRepository;
import jaux.tank.service.system.OperationLogService;
import jaux.tank.utils.DateUtil;
import jaux.tank.utils.PageUtils;
import jaux.tank.utils.factory.Page;

/**
 * Created  on 2018/3/26 0026.
 *
 */
@Service
public class OperationLogServiceImpl implements OperationLogService {
    @Autowired
    private OperationLogRepository operationLogRepository;
    @Override
    public Page getOperationLogs(Page<OperationLog> page, final String beginTime, final String endTime, final String logName, final String logType) {
        Pageable pageable = PageUtils.convertPageToPageable(page);

        org.springframework.data.domain.Page<OperationLog> operationLogPage = operationLogRepository.findAll(new Specification<OperationLog>(){

            @Override
            public Predicate toPredicate(Root<OperationLog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(StringUtils.isNotEmpty(beginTime)){
                    list.add(criteriaBuilder.greaterThan(root.get("createtime").as(Date.class), DateUtil.parseDate(beginTime)));
                }
                if(StringUtils.isNotEmpty(endTime)){
                    list.add(criteriaBuilder.lessThan(root.get("createtime").as(Date.class), DateUtil.parseDate(endTime)));
                }
                if(StringUtils.isNotEmpty(logName)){
                    list.add(criteriaBuilder.like(root.get("logname").as(String.class),logName));
                }
                if(StringUtils.isNotEmpty(logType)){{
                    list.add(criteriaBuilder.equal(root.get("logtype").as(String.class),logType));
                }}
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        },pageable);
        page.setTotal(Integer.valueOf(operationLogPage.getTotalElements()+""));
        page.setRecords(operationLogPage.getContent());
        return page;
    }
}
